package cn.evun.sweet.db;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hsqldb.DatabaseManager;
import org.hsqldb.util.DatabaseManagerSwing;

/**
 * 负责在应用开启或关闭的时候，同步启动数据库服务器
 *
 * @author yangw
 * @since V1.0.0
 */
public class HSQLDBListener implements ServletContextListener {
	
	private HSQLDBCustomLogServer server = null;

	public void contextDestroyed(ServletContextEvent arg0) {
		try{			
			//Class.forName("org.hsqldb.jdbcDriver"); 
			//Connection conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/sweet;shutdown=true", "SA", "");
			//Statement stmt = conn.createStatement(); 
			//stmt.executeUpdate("SHUTDOWN;"); 
			server.shutdownWithCatalogs(org.hsqldb.Database.CLOSEMODE_NORMAL);	
			DatabaseManager.getTimer().shutDown(); 
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	public void contextInitialized(ServletContextEvent event) {
		ServletContext ctx = event.getServletContext();
		server = new HSQLDBCustomLogServer();
		server.setDatabaseName(0, "sweet");
		server.setDatabasePath(0, ctx.getRealPath("/hsqldb/sweet"));
		server.setPort(9001);
		server.setTrace(true);		
		server.start();	
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		DatabaseManagerSwing mgr = new DatabaseManagerSwing();
		mgr.main();
	}
}
